package cn.caishen.report.common.config;

import cn.caishen.report.common.exceptions.BusinessException;
import cn.caishen.report.vo.UserVo;
import lombok.SneakyThrows;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 通过ThreadLocal获取用户信息
 *
 * @author LB
 */
public class LoginInformation {

    public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

    public static String LOGIN_USER = "LOGIN_USER";

    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        map.put(key, value);
    }

    public static Object get(String key) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        return map.get(key);
    }


    public static void setUser(UserVo userVo) {
        if (Objects.isNull(userVo)) {
            set(LOGIN_USER, new UserVo());
        } else {
            set(LOGIN_USER, userVo);
        }
    }

    @SneakyThrows
    public static UserVo getUser() {
        Object o = get(LOGIN_USER);
        if (Objects.isNull(o)) {
            throw new BusinessException("用户未登录，请重新登录");
        } else {
            return (UserVo) get(LOGIN_USER);
        }
    }

}
